package com.xbh.realtime.tio.messageQueue;

import com.jfinal.plugin.redis.Redis;
import com.xbh.realtime.tio.websocket.MyWSMsgHandler;
import redis.clients.jedis.Jedis;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @TioChannelThread: 订阅 TioChannel 的 线程启动器
 * @author: ZBoHang
 * @time: 2021/8/11 15:55
 */
public class TioSubThread extends Thread {

    //订阅者
    private final TioSubscriber tioSubscriber;

    //频道名
    private final String channel = "myChannel";

    public TioSubThread(TioSubscriber tioSubscriber) {
        this.tioSubscriber = tioSubscriber;
    }

    @Override
    public void run() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("定时统计==》当前连接数为：【" + MyWSMsgHandler.getConnectionCount() + "】");
            }
        }, 0, 300000);

        System.out.println("准备订阅-->" + channel);

        Jedis jedis = null;
        try {
            jedis = Redis.use("messageQueue").getJedis();
            jedis.subscribe(tioSubscriber, channel);
            System.out.println(channel + "订阅成功");
        } catch (Exception e) {
            System.out.println(channel + "订阅失败");
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
